package com.example.pyphone3;

import android.content.Intent;
import android.net.Uri;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import org.java_websocket.WebSocket;
import org.java_websocket.WebSocketAdapter;
import org.java_websocket.WebSocketImpl;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.drafts.Draft;
import org.java_websocket.enums.CloseHandshakeType;
import org.java_websocket.enums.HandshakeState;
import org.java_websocket.enums.Opcode;
import org.java_websocket.exceptions.InvalidDataException;
import org.java_websocket.exceptions.InvalidHandshakeException;
import org.java_websocket.framing.Framedata;
import org.java_websocket.handshake.ClientHandshake;
import org.java_websocket.handshake.ClientHandshakeBuilder;
import org.java_websocket.handshake.HandshakeBuilder;
import org.java_websocket.handshake.ServerHandshake;
import org.java_websocket.handshake.ServerHandshakeBuilder;

import client.WebSocketFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.ByteBuffer;

import example.ExampleClient;

import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;

public class WebsocketCon extends Draft {

    URI uri = URI.create("ws://phone.yiyatest.cn/websocket/143/yiya_wh_dd_");
    //    URI uri = URI.create("ws://192.168.10.94");
    JWebSocketClient client = new JWebSocketClient(uri) {
        @Override
        public void onOpen(ServerHandshake handshakedata) {
            Log.e("JWebSClientService", "连接到服务器");
        }

        @Override
        public void onMessage(String message) {
            Log.e("JWebSClientService", message);
        }

        @Override
        public void onClose(int code, String reason, boolean remote) {
            Log.e("JWebSClientService", "未连接\"");
//            tv_title.setText("未连接");
        }

        @Override
        public void onError(Exception ex) {
            Log.e("JWebSClientService", ex.getMessage());
//            tv_title.setText("连接异常");
        }
    };

    void aa() throws IOException, InterruptedException, URISyntaxException {
        WebSocketClient websocket = new ExampleClient(new URI("ws://phone.yiyatest.cn/websocket/143/yiya_wh_dd_"));
        if (!websocket.connectBlocking()) {
            System.err.println("Could not connect to the server.");
            return;
        }

        JWebSocketClient client = new JWebSocketClient(uri) {
            @Override
            public void onOpen(ServerHandshake handshakedata) {
                Log.e("JWebSClientService", "连接到服务器");
            }

            @Override
            public void onMessage(String message) {
                Log.e("JWebSClientService", message);
            }

            @Override
            public void onClose(int code, String reason, boolean remote) {
                Log.e("JWebSClientService", "未连接\"");
//            tv_title.setText("未连接");
            }

            @Override
            public void onError(Exception ex) {
                Log.e("JWebSClientService", "连接异常\"");
//            tv_title.setText("连接异常");
            }
        };

        System.out.println("This example shows how to send fragmented(continuous) messages.");

        BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
        while (websocket.isOpen()) {
            System.out
                    .println("Please type in a loooooong line(which then will be send in 2 byte fragments):");
            String longline = stdin.readLine();
            ByteBuffer longelinebuffer = ByteBuffer.wrap(longline.getBytes());
            longelinebuffer.rewind();

            for (int position = 2; ; position += 2) {
                if (position < longelinebuffer.capacity()) {
                    longelinebuffer.limit(position);
                    websocket.sendFragmentedFrame(Opcode.TEXT, longelinebuffer,
                            false);// when sending binary data one should use Opcode.BINARY
                    assert (longelinebuffer.remaining() == 0);
                    // after calling sendFragmentedFrame one may reuse the buffer given to the method immediately
                } else {
                    longelinebuffer.limit(longelinebuffer.capacity());
                    websocket
                            .sendFragmentedFrame(Opcode.TEXT, longelinebuffer, true);// sending the last frame
                    break;
                }

            }
            System.out.println("You can not type in the next long message or press Ctr-C to exit.");
        }
        System.out.println("FragmentedFramesExample terminated");
    }

    void wsConnect() {
        try {
            client.connectBlocking();
            client = new JWebSocketClient(uri) {
                @Override
                public void onMessage(String message) {
                    Intent intent = new Intent();
                    intent.setAction("com.xch.servicecallback.content");
                    intent.putExtra("message", message);
                }
            };
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    void setMs() {
        if (client != null && client.isOpen()) {
            client.send("你好");
        }
    }

    /**
     * 断开连接
     */
    private void closeConnect() {
        try {
            if (null != client) {
                client.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            client = null;
        }
    }

    @Override
    public HandshakeState acceptHandshakeAsClient(ClientHandshake request, ServerHandshake response) throws InvalidHandshakeException {
        return null;
    }

    @Override
    public HandshakeState acceptHandshakeAsServer(ClientHandshake handshakedata) throws InvalidHandshakeException {
        return null;
    }

    @Override
    public ByteBuffer createBinaryFrame(Framedata framedata) {
        return null;
    }

    @Override
    public List<Framedata> createFrames(ByteBuffer binary, boolean mask) {
        return null;
    }

    @Override
    public List<Framedata> createFrames(String text, boolean mask) {
        return null;
    }

    @Override
    public void processFrame(WebSocketImpl webSocketImpl, Framedata frame) throws InvalidDataException {

    }

    @Override
    public void reset() {

    }

    @Override
    public ClientHandshakeBuilder postProcessHandshakeRequestAsClient(ClientHandshakeBuilder request) throws InvalidHandshakeException {
        return null;
    }

    @Override
    public HandshakeBuilder postProcessHandshakeResponseAsServer(ClientHandshake request, ServerHandshakeBuilder response) throws InvalidHandshakeException {
        return null;
    }

    @Override
    public List<Framedata> translateFrame(ByteBuffer buffer) throws InvalidDataException {
        return null;
    }

    @Override
    public CloseHandshakeType getCloseHandshakeType() {
        return null;
    }

    @Override
    public Draft copyInstance() {
        return null;
    }
}
